<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../css/mui.css" rel="stylesheet" />
		<link href="../css/customize.css" rel="stylesheet" />
		<link rel="stylesheet" type="text/css" href="../css/mui.picker.min.css" />
	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left font-black"></a>
			<h1 class="mui-title">大棚信息</h1>
		</header>
		<div class="mui-content">
			<div class="mui-content-padded">
				<div id="select" class="photo-upload">
					<img src="../image/upload.png" alt="添加照片" class="placeholder-image" id="photo">
				</div>
				<div class="form-container">
					<div class="row form-item">
						<div style="margin-right: 20px;">名称</div>
						<div style="flex: 2;">
							<input type="text" style="margin: 0;border: 0;" placeholder="请输入名称" id="name"
								maxlength="10">
						</div>
					</div>
					<div class="row form-item">
						<div style="margin-right: 20px;">长</div>
						<div style="flex: 2;">
							<div class="mui-row">
								<div class="mui-col-sm-10 mui-col-xs-10">
									<input type="text" style="margin: 0;border: 0;" placeholder="请输入长" id="length"
										maxlength="10">
								</div>
								<div class="mui-col-sm-2 mui-col-xs-2">
									m
								</div>
							</div>
						</div>
					</div>
					<div class="row form-item">
						<div style="margin-right: 20px;">宽</div>
						<div style="flex: 2;">
							<div class="mui-row">
								<div class="mui-col-sm-10 mui-col-xs-10">
									<input type="text" style="margin: 0;border: 0;" placeholder="请输入宽" id="width"
										maxlength="10">
								</div>
								<div class="mui-col-sm-2 mui-col-xs-2">
									m
								</div>
							</div>
						</div>
					</div>

					<div class="row form-item">
						<div style="margin-right: 20px;">高</div>
						<div style="flex: 2;">
							<div class="mui-row">
								<div class="mui-col-sm-10 mui-col-xs-10">
									<input type="text" style="margin: 0;border: 0;" placeholder="请输入高度" id="height"
										maxlength="10">
								</div>
								<div class="mui-col-sm-2 mui-col-xs-2">
									m
								</div>
							</div>
						</div>
					</div>

					<div class="row form-item">
						<div style="margin-right: 20px;">种植面积</div>
						<div style="flex: 2;">
							<div class="mui-row">
								<div class="mui-col-sm-10 mui-col-xs-10">
									<input type="text" style="margin: 0;border: 0;" placeholder="请输入面积" id="area"
										maxlength="10">
								</div>
								<div class="mui-col-sm-2 mui-col-xs-2">
									m²
								</div>
							</div>
						</div>
					</div>

					<div class="row form-item">
						<div style="margin-right: 20px;">种植作物</div>
						<div style="flex: 2;">
							<div class="mui-row">
								<div class="mui-col-sm-10 mui-col-xs-10">
									<input type="text" style="margin: 0;border: 0;" placeholder="请输入作物" id="crop"
										maxlength="50">
								</div>
							</div>
						</div>
					</div>

					<div class="row form-item">
						<div style="margin-right: 20px;">具体位置</div>
						<div style="flex: 2;">
							<input type="text" style="margin: 0;border: 0;" placeholder="请输入具体位置" id="location"
								maxlength="100">
						</div>
					</div>

					<div>
						<div id="map" style="height: 300px;"></div>
					</div>
				</div>

				<div class="form-container" style="margin-top: 1rem;">
					<table style="width:100%;border-collapse:collapse; ">
						<tr>
							<th style="text-align:center;padding:8px;border-bottom:1px solid #eee;">预计价格 (元/斤)</th>
							<th style="text-align:center;padding:8px;border-bottom:1px solid #eee;">预计产量（斤）</th>
						</tr>
						<tr>
							<td style="padding:8px;">
								<input type="text" style="margin: 0;border: 0;width:100%; text-align: center;"
									placeholder="请输入预计价格" id="expectPrice" maxlength="20">
							</td>
							<td style="padding:8px;">
								<input type="text" style="margin: 0;border: 0;width:100%; text-align: center;"
									placeholder="请输入预计产量" id="expectYield" maxlength="20">
							</td>
						</tr>
					</table>
				</div>

				<!-- 销售计划 -->
				<div class="form-container" style="margin-top: 1rem;">
					<h2 style="text-align:center;padding:8px;border-bottom:1px solid #eee;">销售计划</h2>
					<table style="width:100%;border-collapse:collapse; " id="expectTable">
						<!-- <tr>
							<th style="text-align:center;padding:8px;border-bottom:1px solid #eee; width: 60%;">12月-次年2月
							</th>
							<td style="margin: 0;border: 0;width:100%; text-align: center;">40%</td>
						</tr>
						<tr>
							<th style="text-align:center;padding:8px;border-bottom:1px solid #eee; width: 60%;">
								次年2月-次年4月
							</th>
							<td style="margin: 0;border: 0;width:100%; text-align: center;">35%</td>
						</tr>
						<tr>
							<th style="text-align:center;padding:8px;border-bottom:1px solid #eee; width: 60%;">
								次年4月-次年6月
							</th>
							<td style="margin: 0;border: 0;width:100%; text-align: center;">25%</td>
						</tr> -->
					</table>
				</div>

				<div class="mui-row" style="margin-top: 10px;">
					<div class="mui-col-sm-12 mui-col-xs-12">
						<button class="mui-btn mui-btn-green mui-btn-block" id="save">
							保存
						</button>
					</div>
					<div class="mui-col-sm-12 mui-col-xs-12">
						<button class="mui-btn mui-btn-warning mui-btn-block" id="delete">
							删除
						</button>
					</div>
				</div>
			</div>
		</div>
		<script src="../js/mui.js"></script>
		<script src="../js/request.js"></script>
		<script src="../js/storage.js"></script>
		<script src="../js/photo.js"></script>
		<script src="../js/mui.picker.min.js"></script>
		<!--加载高德地图组件-->
		<script src="../js/map.js"></script>
		<script type="text/javascript">
			//定义全局变量
			let ip = localStorage.getItem("ip")
			let imgurl = ""
			//获取当前登录用户
			let user = userCache.getUser();
			let greenhouseId = null;
			let gps = {
				lng: null,
				lat: null,
			}
			let map = null;
			let marker = null;
			GDMapTool.init();
			mui.init({
				beforeback: function() {
					console.log('执行返回')
					//获得列表界面的webview
					var list = plus.webview.getWebviewById('greenhouse.html');
					//触发列表界面的自定义事件（refresh）,从而进行数据刷新
					mui.fire(list, 'refresh');
					//返回true，继续页面关闭逻辑
					return true;
				}
			})

			mui.plusReady(function() {
				let self = plus.webview.currentWebview();
				greenhouseId = self.greenhouseId;
				let del = document.getElementById('delete');
				let map = document.getElementById('map');
				//判断是否为编辑
				if (!greenhouseId) {
					del.style.display = "none";
					map.style.display = "none";
				} else {
					getGreenhouse();

				}
			});


			//选择照片
			document.querySelector("#select").addEventListener("tap", function() {
				TakePhoto.MakePhoto({
					Title: '选择文件',
					Success: function(data) {
						var imgPath = data;
						TakePhoto.UploadImage({
							imgPath: imgPath,
							url: ip + '/common/upload',
							Success: function(res) {
								console.log('url:', res.url)
								res = JSON.parse(res);
								if (res.url) {
									imgurl = res.url.replace(ip, "");
									console.log("imgUrl:", imgurl)
									document.querySelector("#photo").className = 'picture';
									document.querySelector("#photo").src = res.url;
								} else {
									mui.toast("图片上传失败，请重试");
								}
							}
						});
					}
				});
			})

			//注册保存按钮事件监听
			mui("body").on("tap", "#save", function(event) {
				if (greenhouseId != null) {
					updateGreenhouse()
				} else {
					saveGreenhouse()
				}
			})
			//注册删除按钮事件监听
			mui("body").on("tap", "#delete", function(event) {
				if (greenhouseId != null) {
					delHouse()
				}
			})
			//校验
			function valid() {
				let name = document.getElementById('name').value;
				if (!name) {
					mui.toast("请输入名称")
					return false;
				}
				return true;
			}

			//显示地图
			function showMap(lng, lat) {
				//创建地图
				map = GDMapTool.createMap('map', lng, lat)

				//描点
				if (marker) {
					//删除旧的标记
					marker.setMap(null);
				}
				marker = map.marker(lng, lat);
			}

			let State = 0; // 大棚销售计划
			function getGreenhouse() {
				request.get('/system/greenhouse/' + greenhouseId, null, (resp) => {
					let data = resp.data;
					//提交成功回调
					// console.log(JSON.stringify(data));
					document.getElementById('name').value = data.name;
					document.getElementById('location').value = data.location;
					document.getElementById('length').value = data.length;
					document.getElementById('width').value = data.width;
					document.getElementById("height").value = data.height;
					document.getElementById("area").value = data.area;
					document.getElementById("crop").value = data.crop;
					document.getElementById("photo").src = data.picture ? (ip + data.picture) : '../image/upload.png';
					document.getElementById("photo").className = data.picture ? 'picture' : '';
					document.getElementById('expectYield').value = data.area * 0.0015 * 3000;
					document.getElementById('expectPrice').value = data.price;
					imgurl = data.picture ? data.picture : "";
					gps.lng = data.lng;
					gps.lat = data.lat;
					showMap(data.lng, data.lat);

					State = data.state;
					displayGreenhouse();

				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端取大棚详情失败', error);
				})
			}

			// 是否显示大棚销售计划
			function displayGreenhouse() {
				if (State === 0) {
					document.getElementById('expectTable').style.display = 'none';
				} else {
					console.log('greenhouseId',greenhouseId)
					request.get('/system/greenhouse/salesplan/' + greenhouseId,null,(res)=>{
						let data = JSON.stringify(res.data)
						
						let list = document.getElementById('expectTable');
						    
						    // 清空表格（避免重复追加）
						    list.innerHTML = '';
						 
						    // 添加表头（可选）
						    let thead = document.createElement('thead');
						    thead.innerHTML = `
						        <tr>
						            <th style="text-align:center;padding:8px;border-bottom:1px solid #eee; width: 60%;">时间范围</th>
						            <th style="text-align:center;padding:8px;border-bottom:1px solid #eee;">数量</th>
						        </tr>
						    `;
						    list.appendChild(thead);
						 
						    // 添加表格内容
						    let tbody = document.createElement('tbody');
						    res.data.forEach((row) => {
						        let tr = document.createElement('tr');
						        tr.innerHTML = `
						            <td style="text-align:center;padding:8px;border-bottom:1px solid #eee; width: 60%;">${row.timeFrame}</td>
						            <td style="text-align:center;padding:8px;border-bottom:1px solid #eee;">${row.quantity}</td>
						        `;
						        tbody.appendChild(tr); // 插入到 tbody
						    });
						 
						    list.appendChild(tbody); // 把 tbody 插入到 table
					},(err)=>{
						console.log(JSON.stringify(err))
					})
					document.getElementById('expectTable').style.display = '';
				}
			}

			//保存大棚信息
			function saveGreenhouse() {
				if (!valid()) {
					return;
				}
				let name = document.getElementById('name').value;
				let width = document.getElementById('width').value;
				let length = document.getElementById('length').value;
				let height = document.getElementById('height').value;
				let location = document.getElementById('location').value;
				let area = document.getElementById('area').value;
				let crop = document.getElementById('crop').value;
				// let expectPrice = document.getElementById('expectPrice').value;
				// let expectYield = document.getElementById('expectYield').value;
				let data = {
					"name": name,
					"height": height,
					"width": width,
					"length": length,
					"location": location,
					"picture": imgurl,
					"area": area,
					"crop": crop,
					// "expectPrice": expectPrice,
					// "expectYield": expectYield
				}
				request.post('/system/greenhouse', data, (data) => {
					//提交成功回调
					console.log('调用服务端保存大棚成功');
					mui.toast("保存成功");
					mui.back();
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端保存大棚失败', error);
					mui.toast("保存失败");
				})
			}
			//更新大棚信息
			function updateGreenhouse() {
				if (!valid()) {
					return;
				}
				let name = document.getElementById('name').value;
				let width = document.getElementById('width').value;
				let length = document.getElementById('length').value;
				let height = document.getElementById('height').value;
				let location = document.getElementById('location').value;
				let area = document.getElementById('area').value;
				let crop = document.getElementById('crop').value;
				let expectPrice = document.getElementById('expectPrice').value;
				let expectYield = document.getElementById('expectYield').value;
				let data = {
					"id": greenhouseId,
					"name": name,
					"height": height,
					"width": width,
					"length": length,
					"location": location,
					"picture": imgurl,
					"area": area,
					"crop": crop,
					"expectPrice": expectPrice,
					"expectYield": expectYield
				}
				request.put('/system/greenhouse', data, (data) => {
					//提交成功回调
					console.log('调用服务端修改大棚成功');
					mui.toast("保存成功");
					mui.back();
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端修改大棚失败', error);
					mui.toast("保存失败");
				})
			}
			//删除大棚
			function delHouse() {
				request.delete('/system/greenhouse/' + greenhouseId, null, (data) => {
					//提交成功回调
					console.log('调用服务端删除大棚成功');
					mui.toast("删除成功");
					mui.back();
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端删除大棚失败', error);
					mui.toast("删除失败");
				})
			}
		</script>
	</body>

</html>